package org.seckill.web;

import org.seckill.dto.Exposer;
import org.seckill.dto.SeckillExecute;
import org.seckill.dto.SeckillResult;
import org.seckill.entity.Seckill;
import org.seckill.enums.SeckillStateEnum;
import org.seckill.exception.RepeatKillException;
import org.seckill.exception.SeckillCloseException;
import org.seckill.service.SeckillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author jinxd
 * @date 2018/02/09
 */
@Controller
@RequestMapping("/seckill") //url:/模块/资源/{id}/细分 /seckill/list
public class SeckillController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SeckillService seckillService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model) {
        //获取列表页
        List<Seckill> seckills = seckillService.getSeckillList();
        model.addAttribute("list", seckills);
        //list.jsp + model = ModelAndView
        return "list"; //等价于WEB-INF/jsp/"list".jsp
    }

    @RequestMapping(value = "/{seckillId}/detail", method = RequestMethod.GET)
    public String detail(@PathVariable("seckillId") Long seckillId, Model model) {

        if (seckillId == null) {
            return "redirect:/seckill/list";
        }
        Seckill seckill = seckillService.getById(seckillId);
        if (seckill == null) {
            return "forward:/seckill/list";
        }
        model.addAttribute("seckill", seckill);
        return "detail";
    }

    @RequestMapping(value = "/{seckillId}/exposer",
            method = RequestMethod.POST,
            produces = {"application/json;charset=UTF-8"})
    @ResponseBody //springmvc看到此注解，会将返回类型封装成为json
    public SeckillResult<Exposer> exposer(@PathVariable Long seckillId) {
        SeckillResult<Exposer> result;
        try {
            Exposer exposer = seckillService.exportSeckillUrl(seckillId);
            result = new SeckillResult<Exposer>(true, exposer);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new SeckillResult<Exposer>(false, e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/{seckillId}/{md5}/execution",
            method = RequestMethod.POST,
            produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    //phone是通过cookie获取的，设置required是因为当没有killPhone数值时，仍需要接受此映射（即killPhone不是必须的）
    public SeckillResult<SeckillExecute> execute(@PathVariable("seckillId") Long seckillId,
                                                 @PathVariable("md5") String md5,
                                                 @CookieValue(value = "killPhone", required = false) Long phone) {
        //此验证方式可以使用springmvc valid检查
        if (null == phone) {
            return new SeckillResult<SeckillExecute>(false, "未注册");
        }

        //异常信息设置为true，暴露给用户
        SeckillResult<SeckillExecute> result;
        try {
            //改为使用mysql存储过程调用
            SeckillExecute seckillExecute = seckillService.executeSeckillByProcedure(seckillId, phone, md5);
//            SeckillExecute seckillExecute = seckillService.executeSeckill(seckillId, phone, md5);
            result = new SeckillResult<SeckillExecute>(true, seckillExecute);
        } catch (RepeatKillException e) {
            SeckillExecute execute = new SeckillExecute(seckillId, SeckillStateEnum.REPEAT_KILL);
            return new SeckillResult<SeckillExecute>(true, execute);
        } catch (SeckillCloseException e) {
            SeckillExecute execute = new SeckillExecute(seckillId, SeckillStateEnum.END);
            return new SeckillResult<SeckillExecute>(true, execute);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            //未知类型错误均认为是内部错误
            SeckillExecute execute = new SeckillExecute(seckillId, SeckillStateEnum.INNER_ERROR);
            return new SeckillResult<SeckillExecute>(true, execute);
        }
        return result;
    }

    @RequestMapping(value = "/time/now", method = RequestMethod.GET)
    @ResponseBody
    public SeckillResult<Long> time() {
        Date now = new Date();
        return new SeckillResult<Long>(true, now.getTime());

    }
}
